package cs419.magnusmi.trackitcs;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class checkout extends ActionBarActivity {

    //vars for progress bar
    private View mCheckoutView;
    private View mCheckoutStatusView;
    private TextView mCheckoutStatusMessageView;

    //session vars
    String user;
    String API;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkout);

        //setup for progress bar
        mCheckoutView = findViewById(R.id.checkout_view);
        mCheckoutStatusView = findViewById(R.id.checkout_status);
        mCheckoutStatusMessageView = (TextView) findViewById(R.id.checkout_status_message);

        //capture ID and session vars
        Intent i = getIntent();
        String id = i.getStringExtra("id");
        user = i.getStringExtra("user");
        API = i.getStringExtra("API");

        //start progress bar and checkout task
        mCheckoutStatusMessageView.setText(R.string.progress_checkout_item);
        showProgress(true);
        checkOutItem goCheckout = new checkOutItem();
        goCheckout.execute(id);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.checkout, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mCheckoutStatusView.setVisibility(View.VISIBLE);
            mCheckoutStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mCheckoutStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mCheckoutView.setVisibility(View.VISIBLE);
            mCheckoutView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mCheckoutView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mCheckoutStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mCheckoutView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }




    /**
     * Represents an asynchronous login/registration task used to get item list
     * the user.
     */

    public class checkOutItem extends AsyncTask<String, Void, String> {

        //response string and id of item to check out
        String response1 = "";
        String id;

        /**
         * method to perform checkout ops in background
         * @param params id of item to checkout, person checking out item;
         * @return
         */
        @Override
        protected String doInBackground(String... params) {

            //get item to checkout
            id = params[0];
            //DEBUG System.out.println(id);


            //url of PHP to perform checkout ops
            String checkoutstr = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/checkoutItem";

            //execute get request for list, using id retrieved from intent and user from session var
            JSONParser jsonParser = new JSONParser();
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("id", id));
            parameters.add(new BasicNameValuePair("user", user));

            //exectue http operation
            JSONObject json = jsonParser.makeHttpRequest(checkoutstr, "POST", parameters);


            try {
                response1 = json.getString("message");
                //DEBUG System.out.println(response1);
            } catch (JSONException e) {
                Log.d("JSON error", "JSON error");
            }

            return response1;
        }

        /**
         * post execution method to display results and return to inventory screen
         * @param response1
         */
        @Override
        protected void onPostExecute(String response1) {

            //print response from server
            //DEBUG System.out.println(response1);
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, response1, duration);
            toast.show();

            //return to inventory
            //DEBUG System.out.println("checkout done2");
            Intent j = new Intent(getApplicationContext(), Inventory.class);
            Utility.addToIntent(j, user, API);
            startActivity(j);

        }

    }

}
